package com.gulimall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.IService;
import com.common.constant.CartConstant;
import com.common.constant.OrderConstant;
import com.common.to.*;
import com.common.utils.R;
import com.fasterxml.jackson.databind.ser.impl.UnknownSerializer;
import com.gulimall.order.entity.OrderEntity;
import com.gulimall.order.entity.OrderItemEntity;
import com.gulimall.order.enume.OrderStatusEnum;
import com.gulimall.order.feign.CartFeignService;
import com.gulimall.order.feign.MemberFeignService;
import com.gulimall.order.feign.ProductFeignService;
import com.gulimall.order.feign.WareFeignService;
import com.gulimall.order.service.OrderWebService;
import com.gulimall.order.to.OrderCreateTo;
import com.gulimall.order.vo.OrderConfirmVo;
import com.gulimall.order.vo.OrderItemVo;
import com.gulimall.order.vo.OrderSubmitVo;
import com.gulimall.order.vo.SubmitOrderResponseVo;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import javax.swing.tree.MutableTreeNode;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

/**
 * @Author Rookie-6688
 * @Description
 * @Create 2021-04-27 17:59
 */
@Slf4j
@Service
public class OrderWebServiceImpl implements OrderWebService {

    @Resource
    private MemberFeignService memberFeignService;
    @Resource
    private CartFeignService cartFeignService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private ProductFeignService productFeignService;
    @Resource
    private OrderItemServiceImpl orderItemServiceImpl;
    @Resource
    private OrderServiceImpl orderServiceImpl;
    @Resource
    private RabbitTemplate rabbitTemplate;

    /**
     * 获取当前所有购物项信息、收获地址等信息
     *
     * @return
     */
    @Override
    public OrderConfirmVo getOrderConfirm(MemberTo memberTo) throws ExecutionException, InterruptedException {
        OrderConfirmVo orderConfirmVo = new OrderConfirmVo();

        // 获取当前线程的请求头，设置到异步线程的头上去，这样就不会丢失请求头了
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        // 1、远程查询所有的收货地址列表
        CompletableFuture<Void> memberFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);   // 设置请求头
            R r1 = memberFeignService.getAddressListByUserId(memberTo.getId());
            if (r1.getCode() == 0) {
                List<MemberAddressTo> memberAddressToList = r1.getData(new TypeReference<List<MemberAddressTo>>() {
                });
                orderConfirmVo.setMemberAddressVos(memberAddressToList);
            }
        });

        // 2、远程查询购物车所有选中的购物项
        CompletableFuture<Void> orderFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);   // 设置请求头
            List<OrderItemVo> orderItem = cartFeignService.getOrderItem();
            orderConfirmVo.setItems(orderItem);
        }).thenRunAsync(() -> {
            // 3、远程查询仓储
            List<OrderItemVo> items = orderConfirmVo.getItems();
            List<Long> skuIdList = items.stream().map(OrderItemVo::getSkuId).distinct().collect(Collectors.toList());
            R r = wareFeignService.getStockMap(skuIdList);
            if (r.getCode() != 0) {
                log.error("调用远程仓储出错" + r.getCode());
            }
            Map<Long, Integer> stockMap = r.getData(new TypeReference<Map<Long, Integer>>() {
            });
            // 开始封装
            Map<Long, Boolean> map = new HashMap<>();
            for (Long skuId : stockMap.keySet()) {
                if (stockMap.get(skuId) == null || stockMap.get(skuId) <= 0) {
                    map.put(skuId, false);
                } else {
                    map.put(skuId, true);
                }
            }
            orderConfirmVo.setStocks(map);
        });


        // 4、查询用户积分
        orderConfirmVo.setIntegration(memberTo.getIntegration());

        // 5、设置 token，防止重复提交
        String orderToken = UUID.randomUUID().toString();
        stringRedisTemplate.opsForValue().set(OrderConstant.ORDER_TOKEN + memberTo.getId(), orderToken);
        orderConfirmVo.setOrderToken(orderToken);

        // 6、全部执行完返回
        CompletableFuture.allOf(memberFuture, orderFuture).get();
        return orderConfirmVo;
    }

    @Transactional
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo orderSubmitVo, MemberTo memberTo) {
        SubmitOrderResponseVo submitOrderResponseVo = new SubmitOrderResponseVo();

        //1、验证令牌是否合法【令牌的对比和删除必须保证原子性】
        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        String orderToken = orderSubmitVo.getOrderToken();

        //通过lure脚本原子验证令牌和删除令牌
        Long result = stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class),
                Arrays.asList(OrderConstant.ORDER_TOKEN + memberTo.getId()),
                orderToken);

        if (result == 0L) {
            //令牌验证失败，直接返回
            submitOrderResponseVo.setCode(1);
            return submitOrderResponseVo;
        } else {
            //令牌验证成功
            // 获取总的订单对象
            OrderCreateTo orderCreateTo = getOrderCreateTo(orderSubmitVo.getAddrId(), memberTo);

            // 2、将订单数据加入数据库
            saveOrder(orderCreateTo);
            submitOrderResponseVo.setOrder(orderCreateTo.getOrder());

            // 3、验价，比较页面的值和数据库查询的值，如果误差小于0.01就正常（防止中间商品价格发生改变）
            if(Math.abs(orderCreateTo.getOrder().getPayAmount().subtract(orderSubmitVo.getPayPrice()).doubleValue())<0.01){
                // 验价成功
                // 4、锁定库存
                List<WareLock> wareLockList = orderCreateTo.getOrderItems().stream().map(orderItemEntity -> {
                    WareLock wareLock = new WareLock();
                    BeanUtils.copyProperties(orderItemEntity, wareLock);
                    return wareLock;
                }).collect(Collectors.toList());
                OrderTo orderTo = new OrderTo();
                BeanUtils.copyProperties(orderCreateTo.getOrder(),orderTo);
                WareLockTo wareLockTo = new WareLockTo(orderTo.getId(), orderTo.getOrderSn(), wareLockList);
                R r = wareFeignService.lockStock(wareLockTo);
                if(r.getCode() != 0){
                    // 锁失败
                    submitOrderResponseVo.setCode(3);
                }else{
                    submitOrderResponseVo.setCode(0);
                }

                // 5、发送MQ改变订单状态
                rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",orderCreateTo.getOrder());

                return submitOrderResponseVo;
            }else{
                // 验价失败
                submitOrderResponseVo.setCode(2);
                return submitOrderResponseVo;
            }
        }
    }

    /**
     * 保存订单所有数据
     * @param orderCreateTo
     */
    private void saveOrder(OrderCreateTo orderCreateTo) {

        //获取订单信息
        OrderEntity order = orderCreateTo.getOrder();
        order.setModifyTime(new Date());
        order.setCreateTime(new Date());
        //保存订单
        orderServiceImpl.save(order);

        //获取订单项信息
        List<OrderItemEntity> orderItems = orderCreateTo.getOrderItems();
        orderItems.forEach(orderItemEntity -> orderItemEntity.setOrderId(order.getId()));
        //批量保存订单项数据
        orderItemServiceImpl.saveBatch(orderItems);
    }

    /**
     * 获取总的对象
     * @param addressId
     * @param memberTo
     * @return
     */
    private OrderCreateTo getOrderCreateTo(Long addressId,MemberTo memberTo) {
        OrderCreateTo orderCreateTo = new OrderCreateTo();
        // 生成订单号
        String orderSn = IdWorker.getTimeId();
        // 1、生成订单数据
        OrderEntity orderEntity = getOrderEntity(addressId, memberTo, orderSn);

        // 2、生成订单项数据
        List<OrderItemEntity> orderItemEntityList = getOrderItemEntity(orderSn);

        //3、设置优惠、价格、积分等信息
        computePrice(orderEntity,orderItemEntityList);

        orderCreateTo.setOrder(orderEntity);
        orderCreateTo.setOrderItems(orderItemEntityList);

        return orderCreateTo;
    }

    /**
     * 计算优惠、总价格、积分等信息的方法
     * @param orderEntity
     * @param orderItemEntities
     */
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> orderItemEntities) {

        //总价
        BigDecimal total = new BigDecimal("0.0");
        //优惠价
        BigDecimal coupon = new BigDecimal("0.0");
        BigDecimal intergration = new BigDecimal("0.0");
        BigDecimal promotion = new BigDecimal("0.0");

        //积分、成长值
        Integer integrationTotal = 0;
        Integer growthTotal = 0;

        //订单总额，叠加每一个订单项的总额信息
        for (OrderItemEntity orderItem : orderItemEntities) {
            //优惠价格信息
            coupon = coupon.add(orderItem.getCouponAmount());
            promotion = promotion.add(orderItem.getPromotionAmount());
            intergration = intergration.add(orderItem.getIntegrationAmount());

            //总价
            total = total.add(orderItem.getRealAmount());

            //积分信息和成长值信息
            integrationTotal += orderItem.getGiftIntegration();
            growthTotal += orderItem.getGiftGrowth();

        }
        //1、订单价格相关的
        orderEntity.setTotalAmount(total);
        //设置应付总额(总额+运费)
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setCouponAmount(coupon);
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(intergration);

        //设置积分成长值信息
        orderEntity.setIntegration(integrationTotal);
        orderEntity.setGrowth(growthTotal);

        //设置删除状态(0-未删除，1-已删除)
        orderEntity.setDeleteStatus(0);

    }

    /**
     * 生成订单项数据
     * @param orderSn
     * @return
     */
    private List<OrderItemEntity> getOrderItemEntity(String orderSn) {
        List<OrderItemEntity> orderItemEntityList = new ArrayList<>();

        //最后确定每个购物项的价格
        List<OrderItemVo> currentCartItems = cartFeignService.getOrderItem();
        if (currentCartItems != null && currentCartItems.size() > 0) {
            orderItemEntityList = currentCartItems.stream().map((items) -> {
                //构建订单项数据
                OrderItemEntity orderItemEntity = builderOrderItem(items);
                orderItemEntity.setOrderSn(orderSn);
                return orderItemEntity;
            }).collect(Collectors.toList());
        }

        return orderItemEntityList;
    }

    /**
     * 构建单个订单项的数据
     * @param items
     * @return
     */
    private OrderItemEntity builderOrderItem(OrderItemVo items) {

        OrderItemEntity orderItemEntity = new OrderItemEntity();

        //1、商品的spu信息
        Long skuId = items.getSkuId();
        //获取spu的信息
        R spuInfo = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoTo spuInfoData = spuInfo.getData("data", new TypeReference<SpuInfoTo>() {
        });
        orderItemEntity.setSpuId(spuInfoData.getId());
        orderItemEntity.setSpuName(spuInfoData.getSpuName());
        orderItemEntity.setSpuBrand(spuInfoData.getBrandName());
        orderItemEntity.setCategoryId(spuInfoData.getCatalogId());

        //2、商品的sku信息
        orderItemEntity.setSkuId(skuId);
        orderItemEntity.setSkuName(items.getTitle());
        orderItemEntity.setSkuPic(items.getImage());
        orderItemEntity.setSkuPrice(items.getPrice());
        orderItemEntity.setSkuQuantity(items.getCount());

        //使用StringUtils.collectionToDelimitedString将list集合转换为String
        String skuAttrValues = StringUtils.collectionToDelimitedString(items.getSkuAttrValues(), ";");
        orderItemEntity.setSkuAttrsVals(skuAttrValues);

        //3、商品的优惠信息

        //4、商品的积分信息
        orderItemEntity.setGiftGrowth(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());
        orderItemEntity.setGiftIntegration(items.getPrice().multiply(new BigDecimal(items.getCount())).intValue());

        //5、订单项的优惠价格信息
        orderItemEntity.setPromotionAmount(BigDecimal.ZERO);
        orderItemEntity.setCouponAmount(BigDecimal.ZERO);
        orderItemEntity.setIntegrationAmount(BigDecimal.ZERO);

        //当前订单项的实际金额.总额 - 各种优惠价格
        //原来的价格
        BigDecimal origin = orderItemEntity.getSkuPrice().multiply(new BigDecimal(orderItemEntity.getSkuQuantity().toString()));
        //原价减去优惠价得到最终的价格
        BigDecimal subtract = origin.subtract(orderItemEntity.getCouponAmount())
                .subtract(orderItemEntity.getPromotionAmount())
                .subtract(orderItemEntity.getIntegrationAmount());
        orderItemEntity.setRealAmount(subtract);

        return orderItemEntity;
    }

    /**
     * 拼接获取订单对象
     *
     * @param addressId
     * @param memberTo
     * @param orderSn
     * @return
     */
    private OrderEntity getOrderEntity(Long addressId, MemberTo memberTo, String orderSn) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setMemberId(memberTo.getId());
        orderEntity.setOrderSn(orderSn);
        orderEntity.setMemberUsername(memberTo.getUsername());

        // 设置邮费和收货地址
        R r = memberFeignService.getFare(addressId);
        if (r.getCode() != 0) {
            log.error("调用会员服务查询地址邮费发生异常" + r.getCode());
        }
        FareTo fareTo = r.getData(new TypeReference<FareTo>() {
        });
        orderEntity.setFreightAmount(fareTo.getFare());

        //获取到收货地址信息
        MemberAddressTo address = fareTo.getAddress();
        //设置收货人信息
        orderEntity.setReceiverName(address.getName());
        orderEntity.setReceiverPhone(address.getPhone());
        orderEntity.setReceiverPostCode(address.getPostCode());
        orderEntity.setReceiverProvince(address.getProvince());
        orderEntity.setReceiverCity(address.getCity());
        orderEntity.setReceiverRegion(address.getRegion());
        orderEntity.setReceiverDetailAddress(address.getDetailAddress());

        //设置订单相关的状态信息
        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        orderEntity.setAutoConfirmDay(7);
        orderEntity.setConfirmStatus(0);
        return orderEntity;
    }
}
